import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Dashboard from '@/views/Dashboard.vue'
import BookManagement from '@/views/BookManagement.vue'
import ReaderManagement from '@/views/ReaderManagement.vue'
import AdminManagement from '@/views/AdminManagement.vue'
import store from '@/store'

const routes = [
    {
        path: '/',
        redirect: '/dashboard'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: { requiresAuth: false }
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { requiresAuth: true }
    },
    {
        path: '/books',
        name: 'BookManagement',
        component: BookManagement,
        meta: { requiresAuth: true }
    },
    {
        path: '/readers',
        name: 'ReaderManagement',
        component: ReaderManagement,
        meta: { requiresAuth: true }
    },
    {
        path: '/admins',
        name: 'AdminManagement',
        component: AdminManagement,
        meta: { requiresAuth: true, requiresAdmin: true }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const isAuthenticated = store.state.auth.isAuthenticated
    const userRole = store.state.auth.user?.role

    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
    } else if (to.meta.requiresAdmin && userRole !== 'admin') {
        next('/dashboard')
    } else {
        next()
    }
})

export default router